/**
 * network.c
 *
 * network layer radio frequency interface.
 *
 * Copyright (c) sti-seedclass 2011, tankery.chen@gmail.com
 */
#include <LPC11xx.h>
#include <string.h>
#include "network.h"
#include "networkframe.h"
#include "linkrfi.h"

#define FRAME_LIFE      2

static uint8_t address;
static uint8_t workAsNode;
static callback_array upLayerCallback;

static void dataRecvCallback(uint8_t *data, uint32_t len)
{
    if (workAsNode) {
        if (--NETWORK_FRAME_LIFE_BYTE(data) > 0) {
            linkrfiSend(data, len);
        }
    }
	if (upLayerCallback != 0) {
		upLayerCallback(NETWORK_FRAME_DATA_POINTER(data), NETWORK_DATA_SIZE);
	}
}

void networkInit(uint8_t addr, uint8_t isNode)
{
    address = addr;
	workAsNode = isNode;
    linkrfiInit(addr);
	linkrfiSetIntCallback(dataRecvCallback);

	upLayerCallback = 0;
}

void networkSetIntCallback(callback_array func)
{
    upLayerCallback = func;
}

uint32_t networkSend(uint8_t * data, uint32_t len)
{
    uint8_t frame[NETWORK_FRAME_SIZE];

    if (len > NETWORK_DATA_SIZE) {
        return 0;
    }

    memset(frame, 0, NETWORK_FRAME_SIZE);
    NETWORK_FRAME_LIFE_BYTE(frame) = FRAME_LIFE;
    NETWORK_FRAME_ADDR_BYTE(frame) = address;
    memcpy(NETWORK_FRAME_DATA_POINTER(frame), data, len);

    return linkrfiSend(frame, NETWORK_FRAME_SIZE);
}

void networkProcessDuty(void)
{
    linkrfiProcessDuty();
}

uint32_t networkIsWorking(void)
{
    return linkrfiIsWorking();
}

